<template>
  <div class="homework-detail-container">
    <div class="page-header">
      <div class="header-left">
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
      </div>
      <div class="header-title">
        <h1>{{ homework.title }}</h1>
        <el-tag :type="getStatusType(homework.status)">{{ homework.status }}</el-tag>
      </div>
      <div class="header-right">
        <el-button v-if="mode === 'view' && homework.status === '未提交'" type="primary" @click="changeMode('edit')">
          开始答题
        </el-button>
        <el-button v-if="mode === 'edit'" type="success" @click="submitHomework">
          提交作业
        </el-button>
      </div>
    </div>
    
    <div class="homework-info">
      <el-descriptions :column="3" border>
        <el-descriptions-item label="课程名称">{{ course.name }}</el-descriptions-item>
        <el-descriptions-item label="任课教师">{{ course.teacher }}</el-descriptions-item>
        <el-descriptions-item label="发布时间">{{ homework.releaseTime }}</el-descriptions-item>
        <el-descriptions-item label="截止时间">{{ homework.deadline }}</el-descriptions-item>
        <el-descriptions-item label="剩余时间">
          <el-tag :type="getRemainingTimeType(homework.remainingTime)">
            {{ homework.remainingTime }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item v-if="homework.submitTime" label="提交时间">
          {{ homework.submitTime }}
        </el-descriptions-item>
        <el-descriptions-item v-if="homework.gradeTime" label="批改时间">
          {{ homework.gradeTime }}
        </el-descriptions-item>
        <el-descriptions-item v-if="homework.score !== null" label="成绩">
          <span :class="{ 'high-score': homework.score >= 90, 'low-score': homework.score < 60 }">
            {{ homework.score }}
          </span>
        </el-descriptions-item>
      </el-descriptions>
    </div>
    
    <el-divider />
    
    <div class="homework-content">
      <el-card class="content-card">
        <template #header>
          <div class="card-header">
            <span>作业要求</span>
          </div>
        </template>
        <div class="homework-description">
          <p>{{ homework.description }}</p>
          
          <div v-if="homework.questions && homework.questions.length > 0" class="question-list">
            <div v-for="(question, index) in homework.questions" :key="index" class="question-item">
              <h3>{{ index + 1 }}. {{ question.title }}</h3>
              <p>{{ question.description }}</p>
              
              <div v-if="question.type === 'choice'" class="question-choices">
                <el-radio-group v-model="answers[index]" :disabled="mode === 'view' || mode === 'grade'">
                  <el-radio v-for="(choice, choiceIndex) in question.choices" :key="choiceIndex" :label="choice.value">
                    {{ choice.label }}
                  </el-radio>
                </el-radio-group>
              </div>
              
              <div v-else-if="question.type === 'text'" class="question-text">
                <el-input
                  v-model="answers[index]"
                  type="textarea"
                  :rows="4"
                  placeholder="请在此输入您的答案"
                  :disabled="mode === 'view' || mode === 'grade'"
                />
              </div>
              
              <div v-else-if="question.type === 'file'" class="question-file">
                <el-upload
                  v-if="mode === 'edit'"
                  class="upload-demo"
                  action="#"
                  :auto-upload="false"
                  :limit="1"
                  :file-list="fileList[index] || []"
                  @change="(file) => handleFileChange(file, index)"
                >
                  <template #trigger>
                    <el-button type="primary">选择文件</el-button>
                  </template>
                  <template #tip>
                    <div class="el-upload__tip">
                      支持 .doc, .docx, .pdf, .zip 格式文件，且不超过10MB
                    </div>
                  </template>
                </el-upload>
                
                <div v-else-if="answers[index]" class="file-preview">
                  <el-tag type="success">
                    <el-icon><Document /></el-icon>
                    {{ answers[index].name }}
                  </el-tag>
                  <el-button v-if="mode === 'view'" type="primary" link @click="downloadFile(answers[index])">
                    下载
                  </el-button>
                </div>
              </div>
            </div>
          </div>
          
          <div v-else class="content-placeholder">
            <el-empty description="作业内容加载中..." />
          </div>
        </div>
      </el-card>
      
      <el-card v-if="mode === 'grade'" class="feedback-card">
        <template #header>
          <div class="card-header">
            <span>教师评语</span>
          </div>
        </template>
        <div class="teacher-feedback">
          <div class="feedback-score">
            <div class="score-circle" :class="getScoreClass(homework.score)">
              {{ homework.score }}
            </div>
            <div class="score-text">分数</div>
          </div>
          
          <div class="feedback-content">
            <h3>评语</h3>
            <p>{{ homework.feedback || '教师暂未留下评语' }}</p>
            
            <div v-if="homework.questionFeedback && homework.questionFeedback.length > 0" class="question-feedback">
              <h3>详细点评</h3>
              <div v-for="(feedback, index) in homework.questionFeedback" :key="index" class="feedback-item">
                <div class="feedback-header">
                  <span class="question-number">问题 {{ index + 1 }}</span>
                  <span class="question-score">得分：{{ feedback.score }}</span>
                </div>
                <p class="feedback-text">{{ feedback.comment }}</p>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 提交确认对话框 -->
    <el-dialog v-model="submitDialogVisible" title="提交确认" width="30%">
      <p>确定要提交作业吗？提交后仍可在截止日期前修改。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="submitDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 提交成功对话框 -->
    <el-dialog v-model="successDialogVisible" title="提交成功" width="30%" center>
      <div class="success-dialog">
        <el-icon class="success-icon"><CircleCheck /></el-icon>
        <h3>作业提交成功</h3>
        <p>您可以在截止日期前继续修改作业</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleSuccessClose">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Document, CircleCheck } from '@element-plus/icons-vue'
import studentApi from '@/api/modules/student'

const route = useRoute()
const router = useRouter()

// 路由参数
const courseId = computed(() => Number(route.params.courseId))
const homeworkId = computed(() => Number(route.params.homeworkId))
const mode = ref(route.query.mode || 'view')

// 课程信息
const course = ref({})

// 作业信息
const homework = ref({})

// 学生答案
const answers = ref([])

// 文件列表
const fileList = ref({})

// 对话框可见性
const submitDialogVisible = ref(false)
const successDialogVisible = ref(false)

// 初始化数据
const fetchHomeworkDetail = async () => {
  const { data } = await studentApi.getHomeworkDetail(homeworkId.value)
  homework.value = data
  // 可根据mock结构填充answers等
}

onMounted(() => {
  fetchCourseInfo()
  fetchHomeworkDetail()
})

// 获取课程信息
const fetchCourseInfo = () => {
  // 模拟API请求
  setTimeout(() => {
    if (courseId.value === 1) {
      course.value = {
        id: 1,
        name: '高等数学',
        teacher: '王教授',
        icon: 'DataAnalysis',
        color: '#409EFF'
      }
    } else if (courseId.value === 4) {
      course.value = {
        id: 4,
        name: '数据结构',
        teacher: '刘教授',
        icon: 'Connection',
        color: '#F56C6C'
      }
    } else {
      course.value = {
        id: courseId.value,
        name: '未知课程',
        teacher: '未知教师',
        icon: 'Document',
        color: '#909399'
      }
    }
  }, 300)
}

// 获取作业状态对应的类型
const getStatusType = (status) => {
  switch (status) {
    case '未提交': return 'danger'
    case '已提交': return 'warning'
    case '已批改': return 'success'
    default: return 'info'
  }
}

// 获取剩余时间对应的类型
const getRemainingTimeType = (time) => {
  if (time === '已截止') return 'danger'
  if (time.includes('小时') || time === '1天') return 'warning'
  return 'info'
}

// 获取分数对应的样式类
const getScoreClass = (score) => {
  if (score >= 90) return 'score-excellent'
  if (score >= 80) return 'score-good'
  if (score >= 60) return 'score-pass'
  return 'score-fail'
}

// 处理文件上传
const handleFileChange = (file, index) => {
  if (!fileList.value[index]) {
    fileList.value[index] = []
  }
  fileList.value[index] = [file.raw]
  answers.value[index] = file.raw
}

// 下载文件
const downloadFile = (file) => {
  ElMessage.success('文件下载功能已触发')
  // 实际项目中应该调用真实的下载API
}

// 返回上一页
const goBack = () => {
  router.push(`/student/homework`)
}

// 切换模式
const changeMode = (newMode) => {
  mode.value = newMode
}

// 提交作业
const submitHomework = () => {
  // 检查是否有未填写的答案
  const hasEmptyAnswer = answers.value.some((answer, index) => {
    if (homework.value.questions[index].type === 'file') {
      return !answer
    } else {
      return !answer && answer !== 0
    }
  })
  
  if (hasEmptyAnswer) {
    ElMessage.warning('请完成所有题目后再提交')
    return
  }
  
  submitDialogVisible.value = true
}

// 确认提交
const confirmSubmit = () => {
  // 模拟API请求
  setTimeout(() => {
    // 更新作业状态
    homework.value.status = '已提交'
    homework.value.submitTime = new Date().toLocaleString()
    
    submitDialogVisible.value = false
    successDialogVisible.value = true
  }, 500)
}

// 处理提交成功对话框关闭
const handleSuccessClose = () => {
  successDialogVisible.value = false
  mode.value = 'view'
}
</script>

<style lang="scss" scoped>
.homework-detail-container {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .header-title {
      display: flex;
      align-items: center;
      gap: 15px;
      
      h1 {
        margin: 0;
        font-size: 24px;
        font-weight: bold;
        color: #303133;
      }
    }
  }
  
  .homework-info {
    margin-bottom: 20px;
    
    .high-score {
      color: #67C23A;
      font-weight: bold;
    }
    
    .low-score {
      color: #F56C6C;
      font-weight: bold;
    }
  }
  
  .homework-content {
    display: flex;
    flex-direction: column;
    gap: 20px;
    
    .content-card, .feedback-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        span {
          font-size: 16px;
          font-weight: bold;
        }
      }
    }
    
    .homework-description {
      p {
        margin-bottom: 20px;
        line-height: 1.6;
      }
      
      .question-list {
        .question-item {
          margin-bottom: 30px;
          padding-bottom: 20px;
          border-bottom: 1px solid #ebeef5;
          
          &:last-child {
            margin-bottom: 0;
            padding-bottom: 0;
            border-bottom: none;
          }
          
          h3 {
            margin: 0 0 10px;
            font-size: 16px;
            font-weight: bold;
            color: #303133;
          }
          
          p {
            margin-bottom: 15px;
            color: #606266;
          }
          
          .question-choices {
            margin-bottom: 15px;
          }
          
          .question-text {
            margin-bottom: 15px;
          }
          
          .question-file {
            margin-bottom: 15px;
            
            .file-preview {
              display: flex;
              align-items: center;
              gap: 10px;
            }
          }
        }
      }
    }
    
    .teacher-feedback {
      display: flex;
      gap: 30px;
      
      .feedback-score {
        display: flex;
        flex-direction: column;
        align-items: center;
        
        .score-circle {
          width: 80px;
          height: 80px;
          border-radius: 50%;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 24px;
          font-weight: bold;
          color: #fff;
          margin-bottom: 10px;
          
          &.score-excellent {
            background-color: #67C23A;
          }
          
          &.score-good {
            background-color: #409EFF;
          }
          
          &.score-pass {
            background-color: #E6A23C;
          }
          
          &.score-fail {
            background-color: #F56C6C;
          }
        }
        
        .score-text {
          font-size: 14px;
          color: #909399;
        }
      }
      
      .feedback-content {
        flex: 1;
        
        h3 {
          margin: 0 0 10px;
          font-size: 16px;
          font-weight: bold;
          color: #303133;
        }
        
        p {
          margin-bottom: 20px;
          line-height: 1.6;
          color: #606266;
        }
        
        .question-feedback {
          .feedback-item {
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px dashed #ebeef5;
            
            &:last-child {
              margin-bottom: 0;
              padding-bottom: 0;
              border-bottom: none;
            }
            
            .feedback-header {
              display: flex;
              justify-content: space-between;
              margin-bottom: 5px;
              
              .question-number {
                font-weight: bold;
                color: #303133;
              }
              
              .question-score {
                color: #409EFF;
              }
            }
            
            .feedback-text {
              margin: 0;
              color: #606266;
            }
          }
        }
      }
    }
  }
  
  .success-dialog {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px 0;
    
    .success-icon {
      font-size: 60px;
      color: #67C23A;
      margin-bottom: 15px;
    }
    
    h3 {
      margin: 0 0 10px;
      font-size: 18px;
      color: #303133;
    }
    
    p {
      margin: 5px 0;
      color: #606266;
    }
  }
}

// 响应式样式
@media screen and (max-width: 768px) {
  .homework-detail-container {
    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 15px;
      
      .header-left {
        width: 100%;
      }
      
      .header-title {
        width: 100%;
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
      }
      
      .header-right {
        width: 100%;
        display: flex;
        justify-content: flex-end;
      }
    }
    
    .teacher-feedback {
      flex-direction: column;
      
      .feedback-score {
        flex-direction: row;
        gap: 15px;
        margin-bottom: 20px;
      }
    }
  }
}
</style> 